#!/usr/bin/env python
import sys

import carla
import os
import argparse
import shutil
import errno
import json



CARLA_ROOT_PATH = '/home/gj/Carla_0.9.13'


def add_xodr_for_opendrive(target_folder_path, target_name, xodr_files):

    opendrive_xodr_folder_target = os.path.join(
        target_folder_path,
        "Maps",
        target_name,
        "OpenDrive")
    if not os.path.exists(opendrive_xodr_folder_target):
        os.makedirs(opendrive_xodr_folder_target)

    print('Copying "' + xodr_files + '" to "' + opendrive_xodr_folder_target + '"')
    shutil.copy2(xodr_files, opendrive_xodr_folder_target)


def build_json_for_config(target_folder_path, target_name):

    package_name = os.path.basename(target_folder_path)

    maps = {}
    maps["name"] = target_name,
    maps["path"] = "/" + "/".join(["Game", package_name, "Maps", target_name])
    maps["use_carla_materials"] = False

    output_json = {}
    output_json["props"] = []
    output_json["maps"] = []
    output_json["maps"].append({
        "name": maps["name"][0],
        "path": maps["path"],
        "use_carla_materials": maps["use_carla_materials"]
    })

    config_json_folder_target = os.path.join(target_folder_path, "Config")
    if not os.path.exists(config_json_folder_target):
        try:
            os.makedirs(config_json_folder_target)
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise
    with open(os.path.join(config_json_folder_target, package_name + ".Package.json"), "w+") as fh:
        json.dump(output_json, fh, indent=4)
        print('Build "' + package_name + '.Package.json' + '" in floder "' + config_json_folder_target + '"')


def build_binary_for_tm(target_folder_path, target_name, xodr_files):

    tm_binary_folder_target = os.path.join(
        target_folder_path,
        "Maps",
        target_name,
        "TM")
    if not os.path.exists(tm_binary_folder_target):
        os.makedirs(tm_binary_folder_target)

    with open(xodr_files, "rt") as f:
        data = f.read()

    m = carla.Map(str(target_name), data)
    m.cook_in_memory_map(str(os.path.join(tm_binary_folder_target, "%s.bin" % target_name)))
    print('Build "' + target_name + '.bin' + '" in floder "' + tm_binary_folder_target + '"')


def main():
    argparser = argparse.ArgumentParser(description=__doc__)
    argparser.add_argument(
        '--package',
        metavar='P',
        default='map_package',
        help='Name of the imported package')
    argparser.add_argument(
        '--no-carla-materials',
        action='store_false',
        help='user Carla materials')
    argparser.add_argument(
        '--json-only',
        action='store_true',
        help='Create JSON files only')
    argparser.add_argument(
        '--batch-size',
        type=float,
        default=300,
        help='Max batch size in MB')
    args = argparser.parse_known_args()[0]

    # copy_roadpainter_config_files(args.package)
    # import_assets_from_json_list(json_list, args.batch_size)

    CARLA_UE_ROOT_PATH = "/home/gj/Download"
    xodr_files_path = "/home/gj/Download"
    xodr_files_name = "yuxiang.xodr"
    package_name = "aaa"
    xodr_files = os.path.join(xodr_files_path, xodr_files_name)
    target_name = xodr_files_name.split('.')[0]

    target_folder_path = os.path.join(
        CARLA_UE_ROOT_PATH,
        "CarlaUE4",
        "Content",
        package_name)
    if not os.path.exists(target_folder_path):
        os.makedirs(target_folder_path)
    # else:
    # print("该项目已存在，请重新定义下项目名称。")
    # sys.exit(1)

    build_json_for_config(target_folder_path, target_name)

    add_xodr_for_opendrive(target_folder_path, target_name, xodr_files)

    build_binary_for_tm(target_folder_path, target_name, xodr_files)

    static_folder_target = os.path.join(target_folder_path, "Static")
    if not os.path.exists(static_folder_target):
        os.makedirs(static_folder_target)

    # carla_sky_level = "/home/gj/Carla_0.9.13/Unreal/CarlaUE4/Content/Carla/Maps/BaseMap/BaseMap.umap"
    # sky_level_path =
    # shutil.copy2(xodr_files, carla_sky_level)



if __name__ == "__main__":

    try:
        main()
    except KeyboardInterrupt:
        print(' - Exited by user.')
